<template>
  <div>
    <!-- 搜索结果页-头部导航 -->
    <div class="search-result-container">
      <!-- 点击实现后退效果 -->
      <van-nav-bar
        title="搜索结果"
        left-arrow
        @click-left="$router.go(-1)"
        fixed
      />
    </div>
    <!-- 搜索结果显示区 -->
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <div>
        <ArticleItem
          v-for="obj in suggestionList"
          :key="obj.art_id"
          :artObj="obj"
          :isShow="false"
          @click.native="detailFn(obj.art_id)"
        ></ArticleItem>
        <!-- 使用native,能够使用原生的函数 -->
      </div>
    </van-list>
  </div>
</template>

<script>
import { searchResultAPI } from "@/api";
import ArticleItem from "../../components/ArticleItem.vue";
export default {
  components: { ArticleItem },
  name: "SearchResult",

  data() {
    return {
      page: 1, //页码
      suggestionList: [], //搜索结果列表
      //控制加载状态
      loading: false,
      finished: false,
    };
  },
  async created() {
    const res = await searchResultAPI({
      page: this.page, //页数
      per_page: 10, //每个页面的数据数量
      q: this.$route.params.kw,
    });
    if (res.data.data.results.length == 0) {
      this.loading = false;
      this.finished = true;
    } else {
      this.suggestionList = res.data.data.results;
      this.loading = false;
    }

    // console.log(res);
  },
  methods: {
    async onLoad() {
      if (this.suggestionList.length > 0) {
        this.page++;
        //再次发起一次请求
        const res = await searchResultAPI({
          page: this.page, //页数
          per_page: 10, //每个页面的数据数量
          q: this.$route.params.kw,
        });
        if (res.data.data.results.length == 0) {
          this.finished = true;
          return;
        }
        this.suggestionList = [
          ...this.suggestionList,
          ...res.data.data.results,
        ];
        this.loading = false;
      }
    },
    async detailFn(art_id) {
      this.$router.push(`/articledetail?art_id=${art_id}`);
    },
  },
};
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>